using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Routing;
using Thor.Models;
using Thor.WebRole.Services;
using Thor.Common;
using Thor.Domain;
using Thor.Domain.Configuration;

namespace Thor.WebRole.Controllers
{
    public class BookingController : AuthenticatedController
    {
        public ActionResult Index(CalendarEntry entry)
        {
            var result = this.BookingAuthenticationRequired(entry.CalendarEmail);

            if (result != null)
                return result;

            BookingRequest request = new BookingRequest(entry);
            return View("Request", request);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Book(BookingRequest request)
        {
            if (!ModelState.IsValid)
                return View("Request", request);

            var result = this.BookingAuthenticationRequired(request.CalendarEmail);

            if (result != null)
                return result;

            try
            {
                //TODO: this call should be to a domain service that wraps the helper.
                var response = CalendarProviderHelper.BookAppointment(request.CalendarId, request.StartTime, request.EndTime, request.Subject);

                if (response.Success)
                {
                    RouteValueDictionary d = new RouteValueDictionary();
                    d.Add("id", request.CalendarEmail);
                    d.Add("message", response.Message);

                    return RedirectToAction("Booked", "Calendar", d);
                }
                else
                {
                    ModelState.AddModelError("Subject", response.Message);
                    return View("Request", request);
                }
            }
            catch
            {
                RouteValueDictionary d = new RouteValueDictionary();
                d.Add("id", request.CalendarEmail);

                return RedirectToAction("Index", "Calendar", d);
            }
        }
    }
}
